package com.bins.redis.pubsub;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

@Component
public class CrontabTask {

	@Autowired
	private RedisTemplate<String, Serializable> redisTemplate;

	@Scheduled(cron = "* * * * * *") // 每一秒钟执行一次
	public void consumeRedisQueue() {
		ListOperations<String, Serializable> redisList = redisTemplate.opsForList();
		while (true) {
			String params = (String) redisList.rightPop("queue", 2, TimeUnit.SECONDS);
			if (CrontabTask.isJSONValid(params)) {
				JSONObject queue = JSONObject.parseObject(params);
				QueueParams queueParams = JSON.toJavaObject(queue, QueueParams.class);
				System.out.println(queueParams.getSendId());
				System.out.println(queueParams.getContent());
			}
		}
	}

	public static boolean isJSONValid(String test) {
		if (test == null || "".equals(test)) {
			return false;
		}
		try {
			JSONObject.parseObject(test);
		} catch (JSONException ex) {
			try {
				JSONObject.parseArray(test);
			} catch (JSONException ex1) {
				return false;
			}
		}
		return true;
	}

}
